package com.app.service.impl;

import com.app.common.PageBean;
import com.app.common.enums.DataStatusEnum;
import com.app.dao.RecommendRepository;
import com.app.bean.dto.RecommendQueryPage;
import com.app.entity.Recommend;
import com.app.service.IRecommendService;
import com.app.bean.vo.RecommendVO;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @autor xiaoyu.fang
 * @date 2019/10/10 13:39
 */
@Service
public class RecommendServiceImpl implements IRecommendService {

    @Autowired
    private RecommendRepository recommendRepository;

    /**
     * mongodb事务测试
     * 当表为空时，加上事务会报错
     *
     * @param recommend
     */
    @Override
    @Transactional
    public void insert(Recommend recommend) {
        recommend.setDataStatus(DataStatusEnum.VALID.KEY);
        recommend.setCreateAt(new Date());
        recommendRepository.insert(recommend);
    }

    @Override
    public void updateDataStatusById(Integer dataStatus, ObjectId id) {
        recommendRepository.updateDataStatusById(dataStatus, id);
    }

    @Override
    public Recommend findById(ObjectId id) {
        return recommendRepository.findById(id).orElse(null);
    }

    @Override
    public PageBean<Recommend> queryPage(RecommendQueryPage queryPage) {
        queryPage.setDataStatus(DataStatusEnum.VALID.KEY);
        return recommendRepository.queryPage(queryPage);
    }

    @Override
    public List<RecommendVO> queryRecommendation() {
        List<Recommend> recommendList = recommendRepository.queryRecommendation();
        List<RecommendVO> recommendVOS = new ArrayList<>(recommendList.size());
        recommendList.stream().forEach(recommend -> recommendVOS.add(RecommendVO.getVO(recommend)));
        return recommendVOS;
    }
}
